package xin.altitude.delaytask.config;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.altitude.cms.common.util.RabbitUtils;
import xin.altitude.cms.common.util.RedisUtils;
import xin.altitude.delaytask.domain.BuOrder;

import javax.annotation.PostConstruct;

/**
 * @author explore
 * @since 2022/03/07 18:55
 **/
@Component
public class RabbitTemplateConfig implements RabbitTemplate.ConfirmCallback {
    public static final String ORDER_PREFIX = "order::";
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
    }
    
    /**
     * 使用confirm确认，必须提供CorrelationData消息ID信息
     *
     * @param correlationData 相关性数据
     * @param ack             消息投递状态
     * @param cause           可选项
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (correlationData == null) {
            return;
        }
        String key = ORDER_PREFIX + correlationData.getId();
        if (ack) {
            /* 如果消息投递成功，则删除Redis中订单数据，回收内存 */
            RedisUtils.deleteObject(key);
        } else {
            /* 从Redis中读取订单数据，重新投递 */
            BuOrder order = RedisUtils.getObject(key, BuOrder.class);
            /* 重新投递消息 */
            rabbitTemplate.convertAndSend(RabbitmqConfig.DELAY_EXCHANGE_NAME, RabbitmqConfig.DELAY_KEY, order, RabbitUtils.setDelay(30000), RabbitUtils.correlationData(order.getOrderId()));
        }
    }
}
